import { Avatar, AvatarFallback, AvatarImage } from '@radix-ui/react-avatar';
import { Textarea } from '../ui/textarea';
import { Button } from '../ui/button';
import { Send } from 'lucide-react';
import { useState } from 'react';
import { postCreateComment } from '@/axios/taskBoard';
import { firstCase } from '@/helpers';

interface TaskCardCommentsProps {
  taskId: number;
  comments?: TaskComment;
  msg?: boolean
  fullMsg?: boolean
}

export const TaskCardComments = ({ comments, taskId, msg = true }: TaskCardCommentsProps) => {
  const [text, setText] = useState('');
  const [textareaHeight, setTextareaHeight] = useState('30px');

  const handleInputChange = (event: React.ChangeEvent<HTMLTextAreaElement>) => {
    setText(() => event.target.value);
    adjustTextareaHeight(event.target);
  };

  const adjustTextareaHeight = (textarea: HTMLTextAreaElement) => {
    textarea.style.height = textareaHeight;
    textarea.style.height = `${textarea.scrollHeight}px`;
  };

  const sendComment = (e: React.MouseEvent<HTMLButtonElement, MouseEvent>) => {
    e.stopPropagation();
    postCreateComment({
      params: {
        task_id: taskId,
        text
      }
    });
    setText('');
    setTextareaHeight('30px');
  };

  const url = 'https://u13-crm-test.gexarus.com/';

  return (
    <>
      {!!comments?.count && (
        <>
          <div className='mt-1 flex w-full items-start gap-1 border-y py-3'>
            <Avatar className='flex size-7 min-h-7 min-w-7 items-center justify-center overflow-hidden rounded-full bg-slate-100'>
              <AvatarImage src={`${url}${comments.last.userPhoto}`} />
              <AvatarFallback>{firstCase(comments.last.userName)}</AvatarFallback>
            </Avatar>
            <div className='flex w-full flex-col'>
              <h3 className='text-xs font-medium text-slate-700'>{comments.last.userName}</h3>
              <div className='mt-1 flex w-max max-w-[80%] rounded-lg rounded-tl-none border border-slate-400 p-1 px-2'>
                <p className='block text-xs text-slate-600'>{comments.last.text}</p>
              </div>
            </div>
          </div>
        </>
      )}
      {
        msg ? <div className='group flex items-end gap-1 rounded-md border border-[#D9E1E7] focus-within:border-slate-400'>
          <Textarea
            placeholder='Comment this task'
            name='comment task'
            className='max-h-16 min-h-[30px] w-full resize-none overflow-y-hidden border-none p-1 px-2 text-sm placeholder:text-slate-400 focus-visible:ring-offset-[-1] bg-transparent '
            value={text}
            onClick={(e) => e.stopPropagation()}
            onChange={handleInputChange}
            style={{ height: textareaHeight }}
          />
          <Button className='p-2 px-2' variant={'ghost'} onClick={sendComment}>
            <Send size={14} className='text-slate-400 group-focus-within:text-slate-600' />
          </Button>
        </div> : null
      }
    </>
  );
};
